package com.sunshinew.controller;

import com.sunshinew.service.UserService;
import com.sunshinew.utils.DataGridView;
import com.sunshinew.utils.ResultObj;
import com.sunshinew.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;

/**
 * @author 鲜磊
 * @Date 2021/4/9 11:33
 */
@RestController
@RequestMapping("user")
public class UserController {


    @Autowired
    private UserService userService;


    /**
     * 查询所有数据
     * @param userVo
     * @return
     */
    @GetMapping("list")
    public DataGridView loadAllUserList(UserVo userVo){

       return this.userService.loadAllLogInfo(userVo);
    }

    /**
     * 保存
     * @param userVo
     * @return
     */
    @PostMapping("save")
    public ResultObj save(UserVo userVo){
        try {
            this.userService.save(userVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            return ResultObj.ADD_ERROR;
        }
    }


    /**
     * 修改
     * @param userVo
     * @return
     */
    @PutMapping("update")
    public ResultObj update(UserVo userVo){
        try {
            this.userService.updateById(userVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            return ResultObj.UPDATE_ERROR;
        }
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("deleteUser")
    public ResultObj deleteUser(Integer id){
        try {
            this.userService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /**
     * 根据id删除多个用户
     * @param userVo
     * @return
     */
    @RequestMapping("batchDeleteUser")
    public ResultObj batchDeleteUser(UserVo userVo){

        try {
            Collection<Serializable> idList = new ArrayList<>();
            for (Integer id: userVo.getIds()){
                idList.add(id);
            }
            this.userService.removeByIds(idList);
            return  ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }
}
